package com.techsoul.module.accounting.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.poi.ExcelExport;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.accounting.mapper.MaterialSalesPriceMapper;
import com.techsoul.module.accounting.pojo.entity.MaterialSalesPrice;
import com.techsoul.module.accounting.pojo.param.MaterialBuyPriceSaveParam;
import com.techsoul.module.accounting.pojo.param.MaterialSalesPriceSaveParam;
import com.techsoul.module.accounting.pojo.param.MaterialSalesPriceSearchParam;
import com.techsoul.module.accounting.pojo.vo.MaterialBuyPriceVo;
import com.techsoul.module.accounting.pojo.vo.MaterialSalesPriceVo;
import com.techsoul.module.accounting.service.IMaterialSalesPriceService;
import com.techsoul.module.system.service.IConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 销售价格配置基础，用于配置价格，产生最后结算。 Service实现
 *
 * @author liuen
 * @date 2021-04-11
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class MaterialSalesPriceServiceImpl implements IMaterialSalesPriceService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MaterialSalesPriceMapper mapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IConfigService configService;
    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(MaterialSalesPriceSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        MaterialSalesPrice entity = new MaterialSalesPrice();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.mapper.insert(entity);
        return entity.getId();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(MaterialSalesPriceSaveParam params) {
        MaterialSalesPrice entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public MaterialSalesPriceVo findById(String id) {
        return this.mapper.findById(id);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<MaterialSalesPriceVo> findAll(MaterialSalesPriceSearchParam params) {
        return this.mapper.findAll(params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<MaterialSalesPriceVo> findAll(MaterialSalesPriceSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }
    /**
     * 导入模板
     */
    @Override
    public String importTemplate() {
        String baseDir = configService.findByConfigKey("project.attachment.baseDir");
        String baseUrl = configService.findByConfigKey("project.attachment.baseUrl");
        String fileName = "供应商采购价格导入模板.xlsx";
        try {
            new ExcelExport(null, MaterialSalesPriceVo.class).writeFile(baseDir + fileName).close();
        } catch (Exception e) {
            log.error("生成供应商采购价格导入模板失败", e);
            throw new ExcelException(e.getMessage());
        }
        return baseUrl + fileName;
    }

    /**
     * 导入
     * @param file
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String importData(MultipartFile file) {
        List<MaterialSalesPriceVo> dataList = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        int successNum = 0;
        int failureNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(MaterialSalesPriceVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }
        for (MaterialSalesPriceVo data : dataList) {
            try {
                MaterialSalesPriceSaveParam saveParam = new MaterialSalesPriceSaveParam();
                BeanUtils.copyProperties(data, saveParam);
                this.insert(saveParam);
                successNum++;
                successMsg.append("<br/>" + successNum + "导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ExcelException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
